package com.liuqi.loggers.core.converters;

import com.liuqi.loggers.core.Converter;
import com.liuqi.loggers.core.LoggerEvent;

/**
 * converter %class
 *
 * @author liuqi
 * @date 2024/11/5 16:52
 **/
public class ClassConverter implements Converter {

    private static final int out_length = 50;

    private static final String C_S = ANSIConstants.ESC_START + ANSIConstants.CYAN_FG + ANSIConstants.ESC_END;
    private static final String C_E = ANSIConstants.ESC_START + ANSIConstants.ESC_END;

    @Override
    public String convert(LoggerEvent event) {
        return C_S + targetClassName(event.getName()) + C_E;
    }

    @Override
    public String convert0(LoggerEvent event) {
        return targetClassName(event.getName());
    }

    @Override
    public String name() {
        return "logger";
    }

    public String targetClassName(String className) {
        if (className.length() <= out_length) {
            return className;
        }
        StringBuilder buf = new StringBuilder(50);
        int dotIndex = 0;
        int offset = 0;
        while (dotIndex != -1) {
            offset = offset == 0 ? dotIndex + 1 : dotIndex + 2;
            buf.append(className.substring(dotIndex, offset));
            dotIndex = className.indexOf(".", dotIndex + 1);
        }
        buf.append(className.substring(offset));
        return buf.toString();
    }

}
